import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 50000 // request timeout,
})

service.interceptors.request.use(
  config => {
    // 检查URL中是否包含jsessionid参数
    const jsessionidMatch = window.location.href.match(/jsessionid=([^?#;]*)/)
    if (jsessionidMatch && jsessionidMatch[1]) {
      // 如果URL中包含jsessionid，则将其添加到请求URL中
      if (config.url && !config.url.includes(';jsessionid=')) {
        // 分离URL路径和查询参数
        const urlParts = config.url.split('?')
        const path = urlParts[0]
        const query = urlParts[1] ? '?' + urlParts[1] : ''

        // 将jsessionid插入到路径中
        config.url = path + ';jsessionid=' + jsessionidMatch[1] + query
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
